<?php

namespace app\admin\controller\widget;

use albert\services\FormBuilder;
use app\admin\controller\AuthController;
use app\model\system\SystemAttachment;
use app\model\system\SystemAttachmentCategory;
use albert\services\JsonService;
use albert\services\upload\Upload;
use albert\services\UtilService;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 图片相关工具控制器
 * Class ImagesController
 * @package app\admin\controller\widget
 */
class ImagesController extends AuthController
{
    /**
     * 图片列表
     * @return string
     */
    public function index(): string
    {
        $pid = $this->request->param('pid');
        if ($pid === NULL) {
            $pid = session('pid') ? session('pid') : 0;
        }
        session('pid', $pid);
        return $this->fetch('widget/images', ['pid' => $pid]);
    }

    /**
     * 图片列表
     * Author: Albert3306
     * Date: 2021/7/1
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function lst(): string
    {
        $where = UtilService::param([
            ['pid', 0],
            ['page', 1],
            ['limit', 18],
        ], $this->request);
        return JsonService::successful(SystemAttachment::getImageList($where));
    }

    /**
     * 获取分类
     * Author: Albert3306
     * Date: 2021/7/2
     * @param string $name
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getImageCate(string $name = ''): string
    {
        return JsonService::successful(SystemAttachmentCategory::getAll($name));
    }

    /**
     * 上传图片
     * Author: Albert3306
     * Date: 2021/7/2
     * @return string
     */
    public function upload(): string
    {
        $pid = $this->request->param('pid', session('pid'));
        $upload_type = $this->request->param('upload_type', sys_config('upload_type', 1));
        try {
            $upload = new Upload($upload_type);
            $res = $upload->to('attach')->validate()->move();
            if ($res === false) {
                return JsonService::fail('上传失败：' . $upload->getError());
            } else {
                $fileInfo = $upload->getUploadInfo();
                if ($fileInfo) {
                    SystemAttachment::attachmentAdd($fileInfo['name'], $fileInfo['size'], $fileInfo['type'], $fileInfo['dir'], $fileInfo['thumb_path'], $pid, $upload_type, $fileInfo['time']);
                }
                return JsonService::successful('上传成功', ['src' => $res->filePath]);
            }
        } catch (Exception $e) {
            return JsonService::fail('上传失败：' . $e->getMessage());
        }
    }

    /**
     * 删除
     * Author: Albert3306
     * Date: 2021/7/2
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delete()
    {
        $ids = $this->request->param('ids');
        if (empty($ids)) JsonService::fail('还没选择要删除的图片呢？');
        foreach ($ids as $id) {
            if ($id > 0) SystemAttachment::deleteImgAndData($id);
        }
        JsonService::successful('删除成功！');
    }

    /**
     * 添加附件分类
     * Author: Albert3306
     * Date: 2021/7/2
     * @param int $id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function addCate(int $id = 0): string
    {
        $f = [];
        $f[] = FormBuilder::select('pid', '上级分类', (string)$id)->setOptions(SystemAttachmentCategory::getCateList(0, 1))->filterable(1);
        $f[] = FormBuilder::input('name', '分类名称');
        $jsContent = <<<SCRIPT
parent.SuccessCateg();
parent.layer.close(parent.layer.getFrameIndex(window.name));
SCRIPT;
        $form = FormBuilder::make_post_form('添加分类', $f, '/admin/widget/image/saveCate', $jsContent);
        return $this->fetch('public/form-builder', ['form' => $form]);
    }

    /**
     * 添加附件分类
     * Author: Albert3306
     * Date: 2021/7/2
     * @return string
     */
    public function saveCate(): string
    {
        $data = UtilService::param([
            ['pid', 0],
            ['name', ''],
        ], $this->request);
        if (!$data['name']) JsonService::fail('分类名称不能为空！');
        if (SystemAttachmentCategory::create($data)) return JsonService::success('添加成功！');
        return JsonService::fail('添加失败！');
    }

    /**
     * 编辑附件分类
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $id
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function editCate($id): string
    {
        $cate = SystemAttachmentCategory::get($id);
        if (!$cate) return JsonService::fail('数据不存在！');

        $f = [];
        $f[] = FormBuilder::hidden('id', $id);
        $f[] = FormBuilder::select('pid', '上级分类', (string)$cate->getData('pid'))->setOptions(SystemAttachmentCategory::getCateList())->filterable(1);
        $f[] = FormBuilder::input('name', '分类名称', $cate->getData('name'));
        $jsContent = <<<SCRIPT
parent.SuccessCateg();
parent.layer.close(parent.layer.getFrameIndex(window.name));
SCRIPT;
        $form = FormBuilder::make_post_form('编辑分类', $f, '/admin/widget/image/updateCate/' . $id, $jsContent);
        return $this->fetch('public/form-builder', ['form' => $form]);
    }

    /**
     * 编辑附件分类保存
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $id
     * @return string
     */
    public function updateCate($id): string
    {
        $data = UtilService::param([
            ['pid', 0],
            ['name', ''],
        ], $this->request);
        if ($data['pid'] == '') return JsonService::fail('请选择父类！');
        if (!$data['name']) return JsonService::fail('请输入分类名称！');
        SystemAttachmentCategory::edit($data, $id);
        return JsonService::successful('修改成功！');
    }

    /**
     * 删除附件分类
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $id
     * @return string
     */
    public function deleteCate($id): string
    {
        $chdCount = SystemAttachmentCategory::initWhere(['pid' => $id])->count();
        if ($chdCount) return JsonService::fail('有子栏目不能删除！');
        $chdCount = SystemAttachment::initWhere(['pid' => $id])->count();
        if ($chdCount) return JsonService::fail('栏目内有图片不能删除！');
        if (SystemAttachmentCategory::del($id)) return JsonService::successful('删除成功!');
        return JsonService::fail('删除失败');
    }

    /**
     * 移动图片分类
     * Author: Albert3306
     * Date: 2021/7/2
     * @param $images
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function mvCate($images): string
    {
        $f = [];
        $f[] = FormBuilder::hidden('images', $images);
        $f[] = FormBuilder::select('pid', '选择分类')->setOptions(SystemAttachmentCategory::getCateList())->filterable(1);
        $form = FormBuilder::make_post_form('编辑分类', $f, '/admin/widget/image/saveMv');
        return $this->fetch('public/form-builder', ['form' => $form]);
    }

    /**
     * 移动图片分类保存
     * Author: Albert3306
     * Date: 2021/7/2
     * @return string
     */
    public function saveMvCate(): string
    {
        $data = UtilService::param([
            ['pid', 0],
            ['images', ''],
        ], $this->request);
        if (!$data['images']) return JsonService::fail('请选择图片！');
        if ($data['pid'] === '') return JsonService::fail('请选择分类！');
        $res = SystemAttachment::initWhere(['in_att_id' => $data['images']])->update(['pid' => $data['pid']]);
        if ($res) return JsonService::successful('移动成功！');
        return JsonService::fail('移动失败！');
    }
}